package annotation.project;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class CalculatorProxy {

    public static Calculator getCalculator(Calculator calculator){

        InvocationHandler handler=new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Object result =null;
                if(method.isAnnotationPresent(Check.class)){
                    try {
                        result = method.invoke(calculator, args);
                        System.out.println("@Check检查成功");
                    }catch (Exception e){
                        System.out.println("@Check检查出错误");
                        System.out.println(e.getCause().getMessage());
                    }
                }else {
                    System.out.println(method.getDeclaringClass());
                    result = method.invoke(calculator, args);
                }

                return result;
            }
        };

        Object proxyInstance = Proxy.newProxyInstance(calculator.getClass().getClassLoader(), calculator.getClass().getInterfaces(), handler);
        return (Calculator) proxyInstance;

    }
}
